<template>
  <div class="b-form-item">
    <label class="b-form-item-label" :style="{width: Form.labelWidth+'px'}">{{label}}</label>
    <div class="b-form-item-content" :class="alignStyle">
      <slot></slot>
    </div>
    <template v-if="error">
      <div class="b-form-item-error" :style="{left: Form.labelWidth+'px'}">{{error}}</div>
    </template>
  </div>
</template>

<script>
import Schema from 'async-validator'
export default {
  name: 'BFormItem',
  inject: {
    Form: {
      default: ''
    }
  },
  props: {
    prop: {
      type: String
    },
    label: {
      type: String
    },
    align: {
      type: String,
      default: 'left'
    }
  },
  data() {
    return {
      error: ''
    }
  },
  computed: {
    alignStyle () {
      return `b-form-item-content-${this.align}`
    }
  },
  mounted () {
    this.$on('validate', this.validateItem)
  },
  methods: {
    validateItem () {
      let rules = this.Form.rules
      let model = this.Form.model
      let descriptor = rules[this.prop] ? { [`${this.prop}`] : rules[this.prop] } : {}
      let validator = new Schema(descriptor)

      return validator.validate(
        { [`${this.prop}`]: model[this.prop] },
        (error) => {
          if (error) {
            this.error = error[0].message
          } else {
            this.error = ''
          }
        }
      )
    }
  }
}
</script>

<style scoped lang='less'>
</style>